﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Agility.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using OpenAdmin.Core.Consts;

namespace OpenAdmin.HttpApi;

/// <summary>
/// 授权处理程序
/// </summary>
public class PermissionHandler : AgilityAuthorizationHandler
{
    /// <summary>
    /// 处理无策略授权逻辑
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task<bool> HandleNoneRequirementAsync(AuthorizationHandlerContext context)
    {
        //超级管理员不用授权
        var hasSuperAdminString = context.User?.Claims?.FirstOrDefault(p => p.Type == ClaimTypeConsts.HasSuperAdmin)?.Value;
        if (bool.TryParse(hasSuperAdminString, out var hasSuperAdmin) && hasSuperAdmin)
        {
            return Task.FromResult(true);
        }

        //排除权限检查
        var excludePermissions = new List<string>
            {"/api/user/getuserinfo", "/api/permission/getuserpermissionmenus"};

        var httpContext = context.Resource as DefaultHttpContext;
        //请求Url
        var questUrl = httpContext?.Request.Path.Value?.ToLower();

        if (excludePermissions.Any(p => p.ToLower() == questUrl))
        {
            return Task.FromResult(true);
        }

        var userPermissions = context.User?.Claims?.Where(p => p.Type == ClaimTypeConsts.UserApiUrl)
            .Select(p => p.Value)
            .ToList();

        //是否通过认证 && 某用户权限列表中是否有请求的url
        return Task.FromResult(context.User.Identity != null &&
                               userPermissions.Distinct().Any(p => p.ToLower() == questUrl));
    }

    /// <summary>
    /// 处理框架默认提供的策略(AgilityAuthorizationRequirement)授权逻辑
    /// </summary>
    /// <param name="context"></param>
    /// <param name="requirement"></param>
    /// <returns></returns>
    public override Task<bool> HandleAgilityRequirementAsync(AuthorizationHandlerContext context,
        AgilityAuthorizationRequirement requirement)
    {
        return Task.FromResult(true);
    }

    /// <summary>
    /// 处理非AgilityAuthorizationRequirement策略授权逻辑
    /// </summary>
    /// <param name="context"></param>
    /// <param name="requirement"></param>
    /// <returns></returns>
    public override Task<bool> HandleRequirementAsync(AuthorizationHandlerContext context,
        IAuthorizationRequirement requirement)
    {
        return Task.FromResult(true);
    }
}